﻿using System;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone.BackgroundTransfer;

namespace TM.QWeibo.Client.Helper
{
    public class AdHelper
    {

        readonly IsolatedStorageFile _myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        private const string ShareFolder = "/shared/transfers";

        private const string AdFileName = ShareFolder + "/TM.QWeibo.Client.HelperAdHelper.AdFileName.jpg";

        private const string AdFileStoreKey = "TM.QWeibo.Client.HelperAdHelper.AdFileName";

        public  BitmapImage Get()
        {
            try
            {
                if (_myIsolatedStorage.FileExists(AdFileName))
                {
                    var image = new BitmapImage();
                    using (IsolatedStorageFileStream fileStream = _myIsolatedStorage.OpenFile(AdFileName, FileMode.Open))
                    {
                         image.SetSource(fileStream); 
                    }
                    return image;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        private string ImageUrl { get; set; }

        private string TmpLatestAdFilrUrl { get; set; }

        public void Clear()
        {
            try
            {
                LastAdFileUrl = "";
                if (_myIsolatedStorage.FileExists(AdFileName))
                {
                    _myIsolatedStorage.DeleteFile(AdFileName);
                }
            }
            catch
            {
                    
            }
        }

        public void StopTransfer()
        {
            if (BackgroundTransferService.Requests == null) return;
            foreach (var backgroundTransferRequest in BackgroundTransferService.Requests)
            {
                BackgroundTransferService.Remove(backgroundTransferRequest);
            }
        }


        public void Save(string url)
        {
            try
            {
                if (!_myIsolatedStorage.DirectoryExists(ShareFolder))
                {
                    _myIsolatedStorage.CreateDirectory(ShareFolder);
                }
                ImageUrl = url;
                var uri = new Uri(url);
                var transferRequest = new BackgroundTransferRequest(uri)
                                          {
                                              Method = "GET",
                                              TransferPreferences = TransferPreferences.AllowCellularAndBattery,
                                              DownloadLocation = new Uri(AdFileName,UriKind.RelativeOrAbsolute)
                                          };
                transferRequest.TransferStatusChanged += (sender,e)=>{
                    if(e.Request.TransferStatus==TransferStatus.Completed)
                    {
                        LastAdFileUrl = TmpLatestAdFilrUrl;
                    }
                };
                StopTransfer();
                BackgroundTransferService.Add(transferRequest);
            }
            finally
            {
                
            }
        }

        public bool HasAdToBeShow
        {
            get { return _myIsolatedStorage.FileExists(AdFileName); }
        }

        public void CheckIsNew()
        {
            try
            {
                var url =
                    string.Format("http://api.topming.com/advert?mode2={0}&size={1}&height={2}&width={3}&client={4}&client_ver={5}&rnd={6}&ipaddress={7}",
                        "WindowsPhone7",
                        "L",
                        App.Current.Host.Content.ActualHeight,
                        App.Current.Host.Content.ActualWidth,
                        AppSetting.AppName,
                        AppSetting.AppVersion,
                        Guid.NewGuid().ToString(),
                        AppSetting.IpAddress
                        );
                        var request = (HttpWebRequest)WebRequest.Create(url);
                        request.Method = "GET";
                        request.BeginGetResponse((asynchronousResult) =>
                        {
                            try
                            {
                                var request2 = (HttpWebRequest)asynchronousResult.AsyncState;
                                var response = (HttpWebResponse)request2.EndGetResponse(asynchronousResult);
                                var streamResponse = response.GetResponseStream();
                                var streamRead = new StreamReader(streamResponse);
                                var responseString = streamRead.ReadToEnd();
                                streamResponse.Close();
                                streamRead.Close();
                                response.Close();
                                if (!IsNew(responseString))
                                {
                                    TmpLatestAdFilrUrl = responseString;
                                    Save(TmpLatestAdFilrUrl);
                                }
                            }
                            catch
                            {
                                Clear();
                            }

                        }, request);
            }
            catch
            {
                Clear();
            }
        }

        private bool IsNew(string url)
        {
            var old = LastAdFileUrl;
            return string.Equals(url, old, StringComparison.CurrentCultureIgnoreCase);
        }

        private string _lastAdFileUrl="";

        private string LastAdFileUrl
        {
            get
            {
                if(string.IsNullOrWhiteSpace(_lastAdFileUrl))
                {
                    var obj =  Common.Isolated.Get(AdFileStoreKey);
                    if(obj!=null)
                    {
                        _lastAdFileUrl = obj.ToString();
                    }
                }

                return _lastAdFileUrl;
            }
            set
            {
                _lastAdFileUrl = value;
                Common.Isolated.Set(AdFileStoreKey,value);
            }
        }

    }
}
